// Copyright (c) 2023, zongying_cao@163.com
// All rights reserved.
//
// This software is licensed under the MIT License.
use crate::models::LoginInfo;
use crate::utils::panic_if_err;
//use gloo::console;
use crate::errors::MyError;
use crate::services::{get_code_source, get_img_code, login};
use stylist::yew::styled_component;
use wasm_bindgen_futures::spawn_local;
use web_sys::HtmlInputElement;
use yew::{classes, html, use_effect_with, use_node_ref, use_state, Callback, HtmlResult};

#[styled_component]
pub fn App() -> HtmlResult {
    let code_img = use_state(|| String::from(""));
    let user_name_ref = use_node_ref();
    let pwd_ref = use_node_ref();

    {
        let code_img = code_img.clone();
        use_effect_with((), move |_| {
            spawn_local(async move {
                let code_source = panic_if_err(get_code_source().await);
                let img_code = panic_if_err(get_img_code(&code_source).await);
                code_img.set(format!("data:image/png;base64,{}", img_code.img));
            });
        });
    };

    let login_click = {
        let user_name_ref = user_name_ref.clone();
        let pwd_ref = pwd_ref.clone();
        Callback::from(move |_| {
            let user_name: String = panic_if_err(
                user_name_ref
                    .cast::<HtmlInputElement>()
                    .ok_or_else(|| MyError::ElementCastError("user_name_ref".to_string())),
            )
            .value();
            let pwd: String = panic_if_err(
                pwd_ref
                    .cast::<HtmlInputElement>()
                    .ok_or_else(|| MyError::ElementCastError("pwd_ref".to_string())),
            )
            .value();
            let info = LoginInfo { user_name, pwd };
            spawn_local(login(info));
        })
    };

    Ok(html! {
    <div class={classes!("h-100", "row", "content-center", "align-center")}>
        <div>
            <div>
                <table class={classes!(css!(r#"
                        tr {
                          height: 35px;
                        }
                        "#))}>
                    <tr>
                        <td>
                            <label>{"用户名"}</label>
                        </td>
                        <td>
                            <input ref={user_name_ref}/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label>{"密码"}</label>
                        </td>
                        <td>
                            <input ref={pwd_ref}/>
                        </td>
                    </tr>
                </table>
            </div>

            <div>
                <button onclick={login_click}>{"登录"}</button>
            </div>
        </div>
    </div>
        })
}
